//创建用户仓库
import { defineStore } from 'pinia'
import type { loginForm, loginResponseData } from '@/api/user/type.ts'
import type { UserState } from '@/store/modules/types/type.ts'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token.ts'
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'
import router from '@/router'
//引入深拷贝
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
//根据用户的权限来筛选异步路由
const filterAsyncRoute = (asyncRoute: any, routes: string[]) => {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
let useUserStore = defineStore('User', {
  state(): UserState {
    return {
      token: GET_TOKEN(), //用户登录的token
      menuRoutes: constantRoute, //仓库存储生成菜单需要的数组
      username: '', //用户名
      avatar: '', //用户头像
      buttons: [], //存放用户按钮权限
      roles: [], //存放用户角色信息
      routes: [], //存放用户菜单权限
    }
  },
  //异步|逻辑的地方
  actions: {
    async login(data: loginForm) {
      let res: loginResponseData = await reqLogin(data)
      console.log('登录====>', res)
      if (res.code == 200) {
        this.token = res.data as string
        console.log('登录成功====>', this.token)
        //本地存储
        SET_TOKEN(this.token)
        //返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },

    async userInfo() {
      //获取用户信息
      let res = await reqUserInfo()
      console.log('用户信息====>', res)
      if (res.code == 200) {
        this.username = res.data.name
        this.avatar = res.data.avatar
        this.buttons = res.data.buttons
        this.roles = res.data.roles
        this.routes = res.data.routes
        console.log('this.routes==', this.routes)
        //根据用户的权限来筛选异步路由
        let filterRoute = filterAsyncRoute(cloneDeep(asyncRoute), this.routes)
        console.log('filterRoute==', filterRoute)
        //合并路由
        this.menuRoutes = [...constantRoute, ...filterRoute, ...anyRoute]
        //目前路由器管理的只有常量路由；
        //需要将动态路由添加到路由表中

        filterRoute.concat(anyRoute).forEach((item: any) => {
          router.addRoute(item)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    //退出登录
    async logout() {
      let res = await reqLogout()
      console.log('退出登录====>', res)
      if (res.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        this.buttons = []
        this.roles = []
        this.routes = []
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})

//对外暴露
export default useUserStore
